/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jp.co.irep.juten.facade;

import java.util.List;
import java.util.Map;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import jp.co.irep.juten.entity.Product;

/**
 *
 * @author toan_nguyen
 */
@Stateless
public class ProductFacade extends AbstractFacade<Product> {

    @PersistenceContext(unitName = "JutenPU")
    private EntityManager em;

    @Override
    public EntityManager getEntityManager() {
        return em;
    }

    public ProductFacade() {
        super(Product.class);
    }

    public List<Product> find(Map<String, Object> productMap) {
        List<Product> productList;
        EntityManager em = getEntityManager();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Product> cq = cb.createQuery(Product.class);
        Root<Product> product = cq.from(Product.class);
        Predicate cond1 = null, cond2 = null;
        for (Map.Entry<String, Object> entry : productMap.entrySet()) {
            if (entry.getValue() != null) {
                if (entry.getKey().compareTo("name") == 0) {
                    Expression<String> path1 = product.get("name");
                    cond1 = cb.like(path1, (String) entry.getValue());
                }
                if (entry.getKey().compareTo("makerId") == 0 && (Integer) (entry.getValue()) > 0) {
                    Expression<Integer> path2 = product.get("makerId");
                    cond2 = cb.equal(path2, (Integer) (entry.getValue()));

                }
            }
        }
        if (cond2 != null) {
            Predicate cond3 = cb.and(cond1, cond2);
            cq.where(cond3);

        } else {
            cq.where(cond1);

        }
        cq.orderBy(cb.desc(product.get("id")));

        Query query = em.createQuery(cq);

        productList = query.setLockMode(LockModeType.PESSIMISTIC_READ).getResultList();
        return productList;

    }

}
